package com.ja.openchat.ui.found;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.adapters.UserTagGroupsAdapter;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.MobileContactHomeActivity;
import com.ja.openchat.ui.contact.GroupContactHomeActivity;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.model.circle.UserTags;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;
import com.zy.openchat.util.DensityUtil;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

import butterknife.BindView;
import butterknife.OnClick;

public class WhoLookActivity extends JaBaseActivity {

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.all_check_box)
    CheckBox all_check_box;
    @BindView(R.id.check_box)
    CheckBox check_box;
    @BindView(R.id.simi_check_box)
    CheckBox simi_check_box;
    @BindView(R.id.bufen_check_box)
    CheckBox bufen_check_box;
    @BindView(R.id.bukan_check_box)
    CheckBox bukan_check_box;
    @BindView(R.id.ex_bufen_layout)
    View ex_bufen_layout;
    @BindView(R.id.ex_bukan_layout)
    View ex_bukan_layout;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    @BindView(R.id.group_select_content)
    TextView group_select_content;
    @BindView(R.id.contact_select_content)
    TextView contact_select_content;
    @BindView(R.id.group_select_1_content)
    TextView group_select_1_content;
    @BindView(R.id.contact_select_1_content)
    TextView contact_select_1_content;
    @BindView(R.id.bufen_contact_recyclerview)
    SwipeRecyclerView bufen_contact_recyclerview;
    @BindView(R.id.bukan_contact_recyclerview)
    SwipeRecyclerView bukan_contact_recyclerview;

    private CheckBox[] checkBoxes;

    public static void chooseWhoLook(Activity context, int requestCode, int choosePosition, ArrayList<UserInfo> userInfos, ArrayList<ChatInfo> groups, ArrayList<UserTags> userTags) {
        Intent intent = new Intent(context, WhoLookActivity.class);
        intent.putExtra("type", choosePosition);
        if (userInfos != null) {
            intent.putExtra("users", userInfos);
        }
        if (groups != null) {
            intent.putExtra("groups", groups);
        }
        if (userTags != null) {
            intent.putExtra("tags", userTags);
        }
        context.startActivityForResult(intent, requestCode);
    }

    //创建侧滑菜单
    private final SwipeMenuCreator creator = (leftMenu, rightMenu, position) -> {
        SwipeMenuItem deleteItem = new SwipeMenuItem(this)
                .setBackgroundColorResource(R.color.CG2)
                .setImage(R.drawable.image_delete)
                .setText(getString(R.string.delete_text))
                .setTextColor(Color.WHITE)
                .setTextSize(14)
                .setHeight(ViewGroup.LayoutParams.MATCH_PARENT)
                .setWidth(DensityUtil.dp2px(65));
        rightMenu.addMenuItem(deleteItem);
    };
    private ArrayList<UserTags> bufenUserTags = new ArrayList<>();
    private ArrayList<UserTags> bukanUserTags = new ArrayList<>();
    private UserTagGroupsAdapter bufenTagsAdapter;
    private UserTagGroupsAdapter bukanTagsAdapter;

    @Override
    public void initData() {
        setTitle(getString(R.string.who_look_text));
        ArrayList<UserTags> userTags = null;
        if (getIntent() != null) {
            choosePosition = getIntent().getIntExtra("type", WHO_LOOK_TYPE_PUBLIC_ALL);
            if (getIntent().getSerializableExtra("users") != null) {
                if (choosePosition == WHO_LOOK_TYPE_ALLOW_VISIBLE) {
                    chooseUserBufenList = (ArrayList<UserInfo>) getIntent().getSerializableExtra("users");
                } else if (choosePosition == WHO_LOOK_TYPE_DISALLOW_VISIBLE) {
                    chooseUserBukanList = (ArrayList<UserInfo>) getIntent().getSerializableExtra("users");
                }
            }
            if (getIntent().getSerializableExtra("groups") != null) {
                if (choosePosition == WHO_LOOK_TYPE_ALLOW_VISIBLE) {
                    chooseGroupBufenList = (ArrayList<ChatInfo>) getIntent().getSerializableExtra("groups");
                } else if (choosePosition == WHO_LOOK_TYPE_DISALLOW_VISIBLE) {
                    chooseGroupBukanList = (ArrayList<ChatInfo>) getIntent().getSerializableExtra("groups");
                }
            }
            if (getIntent().getSerializableExtra("tags") != null) {
                userTags = (ArrayList<UserTags>) getIntent().getSerializableExtra("tags");
            }
        }
//        toolbar.setBackground(ContextCompat.getDrawable(this, R.drawable.transparent_shape));
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setText(getString(R.string.finish_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("type", choosePosition);
                if (choosePosition == WHO_LOOK_TYPE_ALLOW_VISIBLE) {
                    ArrayList<UserTags> userTags = findCheckedUserTags(bufenUserTags);
                    if (chooseUserBufenList == null && chooseGroupBufenList == null && Common.isEmpty(userTags)) {
                        ToastUtils.showShort(getString(R.string.select_min_one_lable));
                        return;
                    }
                    if (chooseUserBufenList != null) {
                        intent.putExtra("users", chooseUserBufenList);
                    }
                    if (chooseGroupBufenList != null) {
                        intent.putExtra("groups", chooseGroupBufenList);
                    }
                    if (!Common.isEmpty(userTags)) {
                        intent.putExtra("tags", userTags);
                    }
                }
                if (choosePosition == WHO_LOOK_TYPE_DISALLOW_VISIBLE) {
                    ArrayList<UserTags> userTags = findCheckedUserTags(bukanUserTags);
                    if (chooseUserBukanList == null && chooseGroupBukanList == null && Common.isEmpty(userTags)) {
                        ToastUtils.showShort(getString(R.string.select_min_one_lable));
                        return;
                    }
                    if (chooseUserBukanList != null) {
                        intent.putExtra("users", chooseUserBukanList);
                    }
                    if (chooseGroupBukanList != null) {
                        intent.putExtra("groups", chooseGroupBukanList);
                    }
                    if (!Common.isEmpty(userTags)) {
                        intent.putExtra("tags", userTags);
                    }
                }
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });
        checkBoxes = new CheckBox[]{all_check_box, check_box, simi_check_box, bufen_check_box, bukan_check_box};

        choose(choosePosition);
        bufen_contact_recyclerview.setSwipeMenuCreator(creator);
        bufen_contact_recyclerview.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            menuBridge.closeMenu();
            clickDelete(bufenTagsAdapter.getItem(adapterPosition));
        });

        bukan_contact_recyclerview.setSwipeMenuCreator(creator);
        bukan_contact_recyclerview.setOnItemMenuClickListener((menuBridge, adapterPosition) -> {
            menuBridge.closeMenu();
            clickDelete(bukanTagsAdapter.getItem(adapterPosition));
        });

        bufen_contact_recyclerview.setLayoutManager(new LinearLayoutManager(this));
        bufenTagsAdapter = new UserTagGroupsAdapter(bufenUserTags);
        bufen_contact_recyclerview.setAdapter(bufenTagsAdapter);
        UserCircleManager.getIntance().getUserTagsByType(bufenUserTags, 0, choosePosition == WHO_LOOK_TYPE_ALLOW_VISIBLE ? userTags : null, new UserTagsCallback() {
            @Override
            public void onBack(ArrayList<UserTags> userTags) {
                bufenTagsAdapter.notifyDataSetChanged();
            }
        });
        bufenTagsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                UserTags userTags = bufenTagsAdapter.getItem(position);
                userTags.isChecked = !userTags.isChecked;
                bufenTagsAdapter.notifyItemChanged(position);
            }
        });
        bufenTagsAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                UserTags userTags = bufenTagsAdapter.getItem(position);
                UserTagsActivity.editTag(WhoLookActivity.this, REQUEST_EDIT_TAG_CODE, userTags, 0);
            }
        });

        bukan_contact_recyclerview.setLayoutManager(new LinearLayoutManager(this));
        bukanTagsAdapter = new UserTagGroupsAdapter(bukanUserTags);
        bukan_contact_recyclerview.setAdapter(bukanTagsAdapter);
        UserCircleManager.getIntance().getUserTagsByType(bukanUserTags, 1, choosePosition == WHO_LOOK_TYPE_DISALLOW_VISIBLE ? userTags : null, new UserTagsCallback() {
            @Override
            public void onBack(ArrayList<UserTags> userTags) {
                bukanTagsAdapter.notifyDataSetChanged();
            }
        });
        bukanTagsAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull @NotNull BaseQuickAdapter<?, ?> adapter, @NonNull @NotNull View view, int position) {
                UserTags userTags = bukanTagsAdapter.getItem(position);
                userTags.isChecked = !userTags.isChecked;
                bukanTagsAdapter.notifyItemChanged(position);
            }
        });
        bukanTagsAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                UserTags userTags = bukanTagsAdapter.getItem(position);
                UserTagsActivity.editTag(WhoLookActivity.this, REQUEST_EDIT_TAG_CODE, userTags, 1);
            }
        });


    }

    private void clickDelete(UserTags userTags) {
        showProgress();
        UserCircleManager.getIntance().deleteUserTags(userTags, new UserTagCallback() {
            @RequiresApi(api = Build.VERSION_CODES.N)
            @Override
            public void onBack(UserTags userTags) {
                hideProgress();
                bufenUserTags.removeIf(new Predicate<UserTags>() {
                    @Override
                    public boolean test(UserTags now) {
                        return now.id == userTags.id;
                    }
                });
                bukanUserTags.removeIf(new Predicate<UserTags>() {
                    @Override
                    public boolean test(UserTags now) {
                        return now.id == userTags.id;
                    }
                });
                bufenTagsAdapter.notifyDataSetChanged();
                bukanTagsAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError() {
                hideProgress();
            }
        });
    }

    private ArrayList<UserTags> findCheckedUserTags(ArrayList<UserTags> userTags) {
        if (userTags == null || userTags.size() == 0) {
            return null;
        }
        ArrayList<UserTags> userTagsArrayList = new ArrayList<>();
        for (UserTags tags : userTags) {
            if (tags.isChecked) {
                userTagsArrayList.add(tags);
            }
        }
        return userTagsArrayList;
    }


    public void choose(int position) {
        choosePosition = position;
        for (int i = 0; i < checkBoxes.length; i++) {
            CheckBox checkBox = checkBoxes[i];
            checkBox.setChecked(i == choosePosition);
        }
        if (position == WHO_LOOK_TYPE_ALLOW_VISIBLE) {
            ex_bufen_layout.setVisibility(View.VISIBLE);
            showTextByUserList(chooseUserBufenList, contact_select_content);
            showTextByChatList(chooseGroupBufenList, group_select_content);
        } else {
            ex_bufen_layout.setVisibility(View.GONE);
        }
        if (position == WHO_LOOK_TYPE_DISALLOW_VISIBLE) {
            showTextByUserList(chooseUserBukanList, contact_select_1_content);
            showTextByChatList(chooseGroupBukanList, group_select_1_content);
            ex_bukan_layout.setVisibility(View.VISIBLE);
        } else {
            ex_bukan_layout.setVisibility(View.GONE);
        }
    }

    public int choosePosition = WHO_LOOK_TYPE_PUBLIC_ALL;

    private final int REQUEST_GROUP_CODE = 1111;
    private final int REQUEST_GROUP_CODE_1 = 1112;
    private final int REQUEST_USER_CODE = 1113;
    private final int REQUEST_USER_CODE_1 = 1114;
    private final int REQUEST_EDIT_TAG_CODE = 1115;

    public static final int WHO_LOOK_TYPE_PUBLIC_ALL = 0;
    public static final int WHO_LOOK_TYPE_PUBLIC_FRIENDS = 1;
    public static final int WHO_LOOK_TYPE_PRIVTE = 2;
    public static final int WHO_LOOK_TYPE_ALLOW_VISIBLE = 3;
    public static final int WHO_LOOK_TYPE_DISALLOW_VISIBLE = 4;

    private ArrayList<UserInfo> chooseUserBufenList;
    private ArrayList<UserInfo> chooseUserBukanList;
    private ArrayList<ChatInfo> chooseGroupBufenList;
    private ArrayList<ChatInfo> chooseGroupBukanList;

    @OnClick({R.id.public_all_btn, R.id.public_btn, R.id.simi_btn, R.id.bufen_btn, R.id.group_select, R.id.contact_select, R.id.bukan_btn, R.id.group_select_1, R.id.contact_select_1})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.public_all_btn:
                choose(WHO_LOOK_TYPE_PUBLIC_ALL);
                break;
            case R.id.public_btn:
                choose(WHO_LOOK_TYPE_PUBLIC_FRIENDS);
                break;
            case R.id.simi_btn:
                choose(WHO_LOOK_TYPE_PRIVTE);
                break;
            case R.id.bufen_btn:
                choose(WHO_LOOK_TYPE_ALLOW_VISIBLE);
                break;
            case R.id.group_select:
                GroupContactHomeActivity.chooseGroups(this, REQUEST_GROUP_CODE, chooseGroupBufenList);
                break;
            case R.id.contact_select:
                startActivityForResult(MobileContactHomeActivity.getActivityForResult(this, 2, chooseUserBufenList), REQUEST_USER_CODE);
                break;
            case R.id.bukan_btn:
                choose(WHO_LOOK_TYPE_DISALLOW_VISIBLE);
                break;
            case R.id.group_select_1:
                GroupContactHomeActivity.chooseGroups(this, REQUEST_GROUP_CODE_1, chooseGroupBukanList);
                break;
            case R.id.contact_select_1:
                startActivityForResult(MobileContactHomeActivity.getActivityForResult(this, -2, chooseUserBukanList), REQUEST_USER_CODE_1);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        if (data.getSerializableExtra("users") != null) {
            Object users = data.getSerializableExtra("users");
            switch (requestCode) {
                case REQUEST_USER_CODE:
                    chooseUserBufenList = (ArrayList<UserInfo>) users;
                    showTextByUserList(chooseUserBufenList, contact_select_content);
                    break;
                case REQUEST_GROUP_CODE:
                    chooseGroupBufenList = (ArrayList<ChatInfo>) users;
                    showTextByChatList(chooseGroupBufenList, group_select_content);
                    break;
                case REQUEST_USER_CODE_1:
                    chooseUserBukanList = (ArrayList<UserInfo>) users;
                    showTextByUserList(chooseUserBukanList, contact_select_1_content);
                    break;
                case REQUEST_GROUP_CODE_1:
                    chooseGroupBukanList = (ArrayList<ChatInfo>) users;
                    showTextByChatList(chooseGroupBukanList, group_select_1_content);
                    break;
            }
        } else if (data.getParcelableExtra("usertag") != null) {
            UserTags userTags = data.getParcelableExtra("usertag");
            int tagType = data.getIntExtra("type", 0);
            userTags.isChecked = true;
            if (requestCode == REQUEST_USER_CODE) {
                bufenUserTags.add(userTags);
                bufenTagsAdapter.notifyDataSetChanged();
                bukanUserTags.add(userTags.copy());
                bukanTagsAdapter.notifyDataSetChanged();
            } else if (requestCode == REQUEST_USER_CODE_1) {
                bukanUserTags.add(userTags);
                bukanTagsAdapter.notifyDataSetChanged();
                bufenUserTags.add(userTags.copy());
                bufenTagsAdapter.notifyDataSetChanged();
            } else if (requestCode == REQUEST_EDIT_TAG_CODE) {
                ArrayList<UserTags> userTagsArrayList = tagType == 0 ? bufenUserTags : bukanUserTags;
                ArrayList<UserTags> otherUserTagsArrayList = tagType == 0 ? bukanUserTags : bufenUserTags;
                if (userTagsArrayList != null && userTagsArrayList.size() > 0) {
                    for (UserTags tags : userTagsArrayList) {
                        if (tags.id == userTags.id) {
                            tags.isChecked = true;
                            tags.copy(userTags);
                            break;
                        }
                    }
                }
                if (otherUserTagsArrayList != null && otherUserTagsArrayList.size() > 0) {
                    for (UserTags tags : otherUserTagsArrayList) {
                        if (tags.id == userTags.id) {
                            tags.copy(userTags);
                            break;
                        }
                    }
                }
                bufenTagsAdapter.notifyDataSetChanged();
                bukanTagsAdapter.notifyDataSetChanged();
            }
        }
    }

    public static void showTextByUserList(List<UserInfo> userInfos, List<Long> userIds, TextView textView) {
        if (!Common.isEmpty(userInfos)) {
            showTextByUserList(userInfos, textView);
        } else if (!Common.isEmpty(userIds)) {
            StringBuilder stringBuilder = new StringBuilder();
            int length = userIds.size();
            for (int i = 0; i < length; i++) {
                long userId = userIds.get(i);
                UserInfo userInfo = UserInfo.getUserInfo(userId);
                if (userInfo != null) {
                    stringBuilder.append(userInfo.displayName());
                    if (i != (length - 1)) {
                        stringBuilder.append("，");
                    }
                } else {
                    TelegramManager.getTelegramManager().getUserSimpleInfo(userId);
                }
            }
            textView.setText(stringBuilder.toString());
            textView.setVisibility(View.VISIBLE);
        } else {
            textView.setText("");
            textView.setVisibility(View.GONE);
        }
    }

    public static void showTextByUserList(List<UserInfo> userInfos, TextView textView) {
        if (userInfos != null && userInfos.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            int length = userInfos.size();
            for (int i = 0; i < length; i++) {
                UserInfo userInfo = userInfos.get(i);
                stringBuilder.append(userInfo.displayName());
                if (i != (length - 1)) {
                    stringBuilder.append("，");
                }
            }
            textView.setText(stringBuilder.toString());
            textView.setVisibility(View.VISIBLE);
        } else {
            textView.setText("");
            textView.setVisibility(View.GONE);
        }
    }

    private void showTextByChatList(List<ChatInfo> userInfos, TextView textView) {
        if (userInfos != null && userInfos.size() > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            int length = userInfos.size();
            for (int i = 0; i < length; i++) {
                ChatInfo userInfo = userInfos.get(i);
                stringBuilder.append(userInfo.title);
                if (i != (length - 1)) {
                    stringBuilder.append("，");
                }
            }
            textView.setText(stringBuilder.toString());
            textView.setVisibility(View.VISIBLE);
        } else {
            textView.setText("");
            textView.setVisibility(View.GONE);
        }
    }


    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        switch (tg_event.event) {
            case EUser_Td_UpdateContactInfo:
                bufenTagsAdapter.notifyDataSetChanged();
                bukanTagsAdapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_who_look;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
